package com.snake.rabbitmq.routing.consumer;

import com.rabbitmq.client.*;
import com.snake.rabbitmq.utils.MQConnectionUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 邮件消费者
 * @author : jjbin
 * @date : 16:26 2021/5/25
 */

public class ConsumerEmailRouting {
    //队列名称
    private static final String EMAIL_QUEUE = "email_queue_routing";

    //交换机名称
    private static final String DESTINATION_NAME = "my_routing_estination";

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("邮件消费启动");
        //1.建立连接
        Connection connection = MQConnectionUtils.newConnection();
        //2.创建通道
        Channel channel = connection.createChannel();
        //3.消费声明队列
        channel.queueDeclare(EMAIL_QUEUE,false,false,false,null);
        //4.消费者队列绑定交换机 绑定路由 email sms
        channel.queueBind(EMAIL_QUEUE,DESTINATION_NAME,"email");
        channel.queueBind(EMAIL_QUEUE,DESTINATION_NAME,"sms");
        //5.消费监听消息
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"UTF-8");
                System.out.println("邮件消费者获取生产消息:" + msg);
            }
        };
        channel.basicConsume(EMAIL_QUEUE,true,defaultConsumer);
    }
}
